package org.example.mytest.newControler;

import com.alibaba.druid.util.StringUtils;
import org.example.mytest.newentity.LoginUser;
import org.example.mytest.mapper.LoginUserMapper;
import org.example.mytest.utils.JwtUtils;
import org.example.mytest.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;


import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin(origins = "http://localhost:9528", allowCredentials = "true")
public class LoginUserControler {
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/denglu/resider")
    public  int resider(@RequestBody LoginUser loginUser)
    {
        System.out.println(loginUser.getUsername());
        int result =  loginUserMapper.insert(loginUser);
        return result;
    }
    @PostMapping("/loginUser/login")
    public Result login(@RequestBody LoginUser loginUser) {
        // 参数校验
        if (StringUtils.isEmpty(loginUser.getUsername()) || StringUtils.isEmpty(loginUser.getPassword())) {
            return Result.error().message("用户名或密码不能为空");
        }

        // 查询数据库中的用户信息
        LoginUser user = loginUserMapper.selectByUsername(loginUser.getUsername());
        if (user == null) {
            return Result.error().message("用户名不存在");
        }

        // 密码验证(实际项目中应使用加密验证)
        if (!user.getPassword().equals(loginUser.getPassword())) {
            return Result.error().message("密码错误");
        }

        // 生成token
        String token = JwtUtils.generateToken(loginUser.getUsername());

        // 1. 存储「Token→用户」映射（不接收返回值，解决类型冲突）
        String tokenToUserKey = "token:user:" + token;
        stringRedisTemplate.opsForValue().set(
                tokenToUserKey,
                loginUser.getUsername(),
                2,
                TimeUnit.HOURS
        );
        System.out.println("Token→用户映射已存储，键：" + tokenToUserKey); // 仅打印存储动作

        // 2. 存储「用户→Token」映射（补充双向映射）
        String userToTokenKey = "user:token:" + loginUser.getUsername();
        stringRedisTemplate.opsForValue().set(
                userToTokenKey,
                token,
                2,
                TimeUnit.HOURS
        );
        System.out.println("用户→Token映射已存储，键：" + userToTokenKey); // 仅打印存储动作

        return Result.ok().data("token", token);
    }

    @GetMapping("/loginUser/info")
    public Result info(String token) {
        // 解析token获取用户名
        String username = JwtUtils.getClaimsByToken(token).getSubject();
        // 这里可以添加获取用户信息的逻辑
        // 例如：User user = userService.getUserByUsername(username);

        // 返回用户信息，这里只是示例，实际应根据业务需求返回相应数据
        return Result.ok().data("username", username);
    }
    @PostMapping("/loginUser/logout")
    public Result logout(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        System.out.println("登出接口被调用，接收到的Authorization头：" + authHeader);
        // 1. 验证token格式
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return Result.error().message("请先登录");
        }

        // 2. 提取纯token
        String token = authHeader.substring(7);
        System.out.println(token);

        // 3. 执行Redis删除操作
        try {
            // 3.1 获取用户名
            String tokenToUserKey = "token:user:" + token;
            System.out.println("登出查询的键名：" + tokenToUserKey); // 与登录时的tokenToUserKey对比
            String username = stringRedisTemplate.opsForValue().get(tokenToUserKey);
            System.out.println("查询到的用户名：" + username);

            // 3.2 删除用户-TOKEN映射
            if (username != null) {
                String userTokenKey = "user:token:" + username;
                Boolean del1 = stringRedisTemplate.delete(userTokenKey);
                System.out.println("删除 user:token:" + username + " 结果：" + (del1 ? "成功" : "失败（键不存在）"));
            }

// 3.3 删除TOKEN-用户映射
            String tokenUserKey = "token:user:" + token;
            Boolean del2 = stringRedisTemplate.delete(tokenUserKey);
            System.out.println("删除 token:user:" + token + " 结果：" + (del2 ? "成功" : "失败（键不存在）"));
            return Result.ok().message("登出成功");
        } catch (Exception e) {
            return Result.error().message("登出失败：" + e.getMessage());
        }
    }
}


